"use client";
import { mergeObj } from "@/lib/util";
import { Spin, SpinProps } from "antd";
import { ReactNode, useEffect, useState } from "react";
/**自定义的加载组件的props */
export interface LoadingProps extends SpinProps {
  /**加载时是否需要展示时间 */
  showtime?: boolean;
  /**要展示的其它内容 （会在时间的下面） */
  otherRender?: (nowTime: number) => ReactNode;
}
let timer: NodeJS.Timeout | null;
/**加载组件，二次封装Spin，给加载文案加了个时间 */
export default function Loading(props: LoadingProps) {
  const { showtime = false, otherRender, ...antdProps } = props;
  const [nowTime, setNowTime] = useState(0);
  const needShowTip = !!(showtime || otherRender); //是否需要展示tip
  useEffect(() => {
    if (antdProps.spinning) {
      timer = setInterval(() => {
        setNowTime((val) => val + 1);
      }, 1000);
    } else {
      if (timer) clearInterval(timer);
      timer = null;
      setNowTime(0);
    }
  }, [antdProps.spinning]);
  const Tip = () => {
    if (antdProps.children)
      return (
        <>
          {showtime ? <div>{nowTime}s</div> : undefined}
          {otherRender && otherRender(nowTime)}
        </>
      );
  };
  return <Spin {...mergeObj({ tip: needShowTip ? Tip() : undefined }, antdProps)}>{antdProps.children}</Spin>;
}
